<cfcomponent extends="assets.csac.com.Base">

	<cfscript>
        import assets.csac.com.service.OrderService;
		this.service = new OrderService();
	</cfscript>

	<cffunction name="get" output="false" access="remote" returntype="assets.csac.com.bo.Order">
		<cfreturn this.service.get(argumentCollection = arguments) />
	</cffunction>
	
	<cffunction name="query" output="false" access="public" returntype="query">
		<cfreturn this.service.read(argumentCollection = arguments) />
	</cffunction>
	
	<cffunction name="save" output="false" access="public" returntype="any">
        <cfscript>
			var order = "";
			var order_ = this.service.get(Order_ID = arguments.Order_ID);
			var orderProductGateway = "";
			var opArgs = "";
			var orderProduct = "";
			if (IsInstanceOf(arguments[1], "assets.csac.com.bo.Order")) {
				order = arguments[1];
			} else {
				var args = {};
				StructAppend(args, arguments);
				args.obj = Duplicate(order_);
				order = this.service.load(argumentCollection = args);
			}
			if (order.getOrder_ID() eq 0) {
				order.setOrder_Date(DateFormat(Now(), "m/d/yyyy"));
			} 
			// validation
			order.setOrder_ID(this.service.save(order));
			// save Order Products
			if (StructKeyExists(args, "Order_Product_ID") AND StructKeyExists(args, "Product_ID")) {
				orderProducts = [];
				orderProductGateway = new assets.csac.com.gateway.OrderProductGateway();
				for (i=1; i lte ListLen(args.Order_Product_ID); i++) {
					opArgs = {};
					opArgs.Order_Product_ID = ListGetAt(args.Order_Product_ID, i);
					opArgs.Order_ID = order.getOrder_ID();
					opArgs.Product_ID = ListGetAt(args.Product_ID, i);
					opArgs.Quantity = args["Quantity_" & opArgs.Product_ID];
					opArgs.Quantity_Shipped = args["Quantity_Shipped_" & opArgs.Product_ID];
					orderProduct = orderProductGateway.save(argumentCollection = opArgs);
					ArrayAppend(orderProducts, orderProduct);
				}
			}
			if (order_.getOrder_ID() eq 0 AND order.getWMS_Order_ID() eq 0) {
				order.setStatus("Approved");
				order.setOrder_ID(this.service.save(order));
			}
			if (order.getStatus() eq "New" or order.getStatus() eq "On Hold") {
				order.setApproved_Date("");
				order.setShipped_Date("");
				order.setOrder_ID(this.service.save(order));
			}
			if (order_.getStatus() neq "Approved" and order.getStatus() eq "Approved") {
				order.setApproved_Date(DateFormat(Now(), "m/d/yyyy"));
				order.setOrder_ID(this.service.save(order));
			}
			return order;
        </cfscript>
	</cffunction>
	
	<cffunction name="delete" output="false" access="public" returntype="boolean">
		<cfreturn this.service.destroy(argumentCollection = arguments) />
	</cffunction>

</cfcomponent>